package com.awccis.customer.controller;

import cn.jpush.api.push.model.PushPayload;
import com.awccis.admin.model.sorder.ServiceOrderSimpleBean;
import com.awccis.common.pool.CustomerPool;
import com.awccis.common.pool.DriverPool;
import com.awccis.common.session.DriverSession;
import com.awccis.common.utils.*;
import com.awccis.customer.model.CustomerInfo;
import com.awccis.customer.model.UsualAddr;
import com.awccis.customer.model.adver.AdverImgLocationBean;
import com.awccis.customer.model.order.AppraiseBean;
import com.awccis.customer.model.order.OrderBean;
import com.awccis.customer.model.order.OrderInfo;
import com.awccis.customer.service.CustomerService;
import com.awccis.driver.model.credit.CreditBean;
import com.awccis.driver.service.DriverService;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author: zhou
 * @Date: 2018-04-15 15:03
 * @Since: 1.0
 * @Description: customer端接口
 **/
@Controller
@RequestMapping(value = "/customer", method = RequestMethod.POST)
public class CustomerController {

    @Resource
    private CustomerService customerService;

    @Resource
    private DriverService driverService;

    /**
     * 日志打印对象
     */
    private Logger logger = LoggerFactory.getLogger(CustomerController.class);

    /**
     * spring线程池
     */
    @Resource
    ThreadPoolTaskExecutor cacheExecutor;

    /**
     * 乘客端验证登陆信息，
     *
     * @param customerInfo {"customerPhone":12345678910, "customerPasswd":"123123"}
     * @return Object
     */
    @RequestMapping(value = "/customerLogin", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Object customerLogin(@RequestBody CustomerInfo customerInfo) {
        Map<String, Object> map = new HashMap<>();
        String customerPhone = customerInfo.getCustomerPhone();
        String customerPasswd = customerInfo.getCustomerPasswd();
        //非空校验
        if ("".equals(customerPhone) || "".equals(customerPhone.trim()) ||
                "".equals(customerPasswd) || "".equals(customerPasswd.trim())) {
            map.put(Constants.MAP_KEY_RESULT, "用户名或密码不能包含空格");
        } else {
            //判断用户名密码是否正确
            customerInfo.setCustomerPasswd(MD5Utils.MD5(customerInfo.getCustomerPasswd()));
            CustomerInfo customer = customerService.getCustomerLoginInfo(customerInfo);
            if (customer == null) {
                map.put("result", false);
                map.put("message", "用户名或密码错误");
            } else if (CustomerPool.isContain(customerPhone)) {
                map.put("result", false);
                map.put("message", "账号已经登录");
            } else {
                //设置登录状态为在线
//                customerService.setOnline(customerPhone);
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, customer);
            }
        }
        return map;
    }

    /**
     * 乘客端注销
     *
     * @param customerInfo {"customerPhone":12345678910, "customerPasswd":123}
     * @return Object
     */
    @RequestMapping(value = "/customerLogout", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Object customerLogout(@RequestBody CustomerInfo customerInfo) {
        Map<String, Object> map = new HashMap<>();
        boolean isLogin = CustomerPool.isContain(customerInfo.getCustomerPhone());
        if (isLogin) {
            if (CustomerPool.deleteCustomerByPhone(customerInfo.getCustomerPhone())) {
                map.put(Constants.MAP_KEY_RESULT, true);
            } else {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "未知错误");
            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "账号未登录");
        }
        return map;
    }


    /**
     * 乘客端注册信息
     *
     * @param customerInfo {"customerName":"aaa","customerGender":"男","customerSchool":"aaaa","customerPhone":12345678910, "customerPasswd":123456}
     * @return Object
     */
    @RequestMapping(value = "/customerRegister", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Object customerRegister(@RequestBody CustomerInfo customerInfo) {
        Map<String, java.io.Serializable> map = new HashMap<>();
        boolean result = false;
        //String gender = customerInfo.getCustomerGender();
        String name = customerInfo.getCustomerName();
        //String school = customerInfo.getCustomerSchool();
        String phone = customerInfo.getCustomerPhone();
        String passwd = customerInfo.getCustomerPasswd();

        if (name == null || "".equals(name)) {
            map.put(Constants.MAP_KEY_MESSAGE, "姓名不能为空");
        } else if (phone == null || "".equals(phone)) {
            map.put(Constants.MAP_KEY_MESSAGE, "手机号不能为空");
        } else if (passwd == null || "".equals(passwd)) {
            map.put(Constants.MAP_KEY_MESSAGE, "密码不能为空");
        } else {
            customerInfo.setCustomerPasswd(MD5Utils.MD5(customerInfo.getCustomerPasswd()));
            result = customerService.registerCustomer(customerInfo);
        }
        map.put(Constants.MAP_KEY_RESULT, result);
        return map;
    }

    /**
     * 更改乘客信息
     *
     * @param customerInfo {"customerPhone": "+8615380863429", "customerName": "测试", "customerGender": "男", "customerSchool": "哈哈哈"}
     * @return {}
     */
    @RequestMapping(value = "/completeCustomerInfo", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map<String, Object> completeCustomerInfo(@RequestBody CustomerInfo customerInfo) {
        logger.info("乘客更新个人信息" + customerInfo.toString());

        Map<String, Object> map = new HashMap<>();

        if (customerInfo.getCustomerPhone() != null) {
            boolean result = customerService.updateCustomerInfo(customerInfo);
            map.put(Constants.MAP_KEY_RESULT, result);
            if (result) {
                map.put(Constants.MAP_KEY_MESSAGE, "更改成功！");
            } else {
                map.put(Constants.MAP_KEY_MESSAGE, "更改失败！");
            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "非法请求参数！");
        }

        return map;
    }

    /**
     * 计算价钱
     *
     * @param orderInfo {"distance": 123.33}
     * @return {"result": 323.6}
     */
    @RequestMapping(value = "/calculatePrice", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Object calculatePrice(@RequestBody OrderInfo orderInfo) {
        Map<String, java.io.Serializable> map = new HashMap<>();

        JsonObject obj;
        JsonArray routes;
        double distanceSum = 0;
        double durationSum = 0;
        String[] urls = orderInfo.getRouterUrl().split("\\?");
        try {
            obj = JsonUtil.str2obj(HttpRequestUtil.sendGet(urls[0], urls[1]), JsonObject.class);
            routes = obj.getAsJsonArray("routes");
            //distanceSum =legs.get(0).getAsJsonObject().get("distance").getAsJsonObject().get("value").getAsDouble();
            //durationSum =legs.get(0).getAsJsonObject().get("duration").getAsJsonObject().get("value").getAsDouble();

            double minDistance = 0;

            JsonArray leg1 = routes.get(0).getAsJsonObject().getAsJsonArray("legs");
            for (int k = 0; k < leg1.size(); k++) {
                minDistance += routes.get(0).getAsJsonObject().getAsJsonArray("legs").get(k).getAsJsonObject().get("distance").getAsJsonObject().get("value").getAsDouble();
            }
            logger.info("第一个路线规划的距离" + minDistance);
            for (int i = 0; i < routes.size(); i++) {
                double distance = 0;
                double time = 0;
                JsonArray legsArray = routes.get(i).getAsJsonObject().getAsJsonArray("legs");
                for (int z = 0; z < legsArray.size(); z++) {
                    distance += routes.get(i).getAsJsonObject().getAsJsonArray("legs").get(z).getAsJsonObject().get("distance").getAsJsonObject().get("value").getAsDouble();
                    time += routes.get(i).getAsJsonObject().getAsJsonArray("legs").get(z).getAsJsonObject().get("duration").getAsJsonObject().get("value").getAsDouble();
                }
                logger.info("第" + i + "距离" + distance);
                if (minDistance >= distance) {
                    minDistance = distance;
                    distanceSum = distance;
                    durationSum = time;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.warn(e.toString());
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "价格计算失败!");
            return map;
        }

        double price = 0;
        if (0 < distanceSum && distanceSum < 9999999) {
            price = customerService.calculatePrice(distanceSum / 1000);
            map.put(Constants.MAP_KEY_RESULT, true);
            map.put("distance", distanceSum);
            map.put("duration", durationSum);
            map.put("price", price);
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "非法请求值");
        }
        return map;
    }

    @GetMapping(value = "/testCreateOrUpdateOrder")
    public @ResponseBody
    Object testCreateOrUpdateOrder(@RequestParam Integer id) {
            OrderBean orderBean=new OrderBean();

            orderBean.setDriverNickName(id);
            orderBean.setDriverId(id);
            orderBean.setCustomerId(2);
            orderBean.setStatusId(1);
            orderBean.setCustomerName("aaa");
            orderBean.setOrderCost(55.6);
            orderBean.setOrderTravelOnPlace("六合");
            orderBean.setOrderOnPlaceLong(32.127481546);
            orderBean.setOrderOnPlaceLai(113.2456321);
            orderBean.setOrderTravelEndPlace("南京");
            orderBean.setOrderEndPlaceLong(32.1545421245);
            orderBean.setOrderEndPlaceLai(113.12545465478);
            orderBean.setOrderCustomerCount(3);
            orderBean.setOrderDistance(20.5);
            int count = 0;
        int result = customerService.insertOrderInfoInit(orderBean);
            //先通过内存池中获取session，然后获取driver的Phone
            DriverSession session = DriverPool.getSessionById(orderBean.getDriverId());
            session.setWork(true);
            orderBean.setDriverPhone(session.getDriverPhone());
            //极光推送
            PushPayload pushPayload = MessagePushUtil.pushAndroidAndIosByAlias(orderBean.getDriverId()+ "", "订单推送","有乘客需要乘车","AA");
            MessagePushUtil.sendPushTryCatch(pushPayload);
            boolean b = DriverPool.sendMessageByNickName(orderBean.getDriverNickName(), "sendMessage2driver:" + JsonUtil.json2str(orderBean));
            if(b){
                return "发送成功";
            }
            else{
                return "发送失败";
            }
    }

    /**
     * 根据乘客的提供信息，向数据库中订单表插入初始信息，
     * 并且寻找在此乘客附近的司机，然后将司机信息推送给乘客，
     * 推荐司机
     *
     * @param orderBean {
     *                  "customerId": 2
     *                  ,"statusId":0
     *                  ,"customerName":"aaa"
     *                  ,"orderCost":55.6
     *                  ,"orderTravelOnPlace":"睢宁县"
     *                  ,"orderOnPlaceLong":32.127481546
     *                  ,"orderOnPlaceLai":113.2456321
     *                  ,"orderTravelEndPlace":"南京"
     *                  ,"orderEndPlaceLong":32.1545421245
     *                  ,"orderEndPlaceLai":113.12545465478
     *                  ,"orderCustomerCount":3
     *                  ,"orderDistance":20.5
     *                  <p>
     *                  }
     * @return {"result":true}
     */
    @RequestMapping(value = "/createOrUpdateOrder", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Object createOrUpdateOrder(@RequestBody OrderBean orderBean) {
        Map<String, java.io.Serializable> map = new HashMap<>();

        if (orderBean.getCustomerName() == null) {
            //提交的数据有误，返回数据，，订单有误，请重新提交数据
            map.put(Constants.MAP_KEY_RESULT, "error");
            return map;
        }
        int result = customerService.insertOrderInfoInit(orderBean);

        //这里是初始订单表数据插入成功，下面执行的查找在提交的customer的附近位置进行寻找司机，并将司机的个人信息返回给customer
        if (result != 0) {
            logger.info("消息推送：" + orderBean.getDriverNickName());
            if (orderBean.getDriverNickName() != 0) {
                //改用线程池
                cacheExecutor.execute(() -> {
                    int count = 0;

                    //先通过内存池中获取session，然后获取driver的Phone
                    DriverSession session = DriverPool.getSessionById(orderBean.getDriverId());
                    session.setWork(true);
                    orderBean.setDriverPhone(session.getDriverPhone());
                    String s = customerService.sendOrderInfoToDriver(orderBean);
                    logger.info("给司机发送订单通知短信结果数据：" + s);
                    //极光推送
                    PushPayload pushPayload = MessagePushUtil.pushAndroidAndIosByAlias(orderBean.getDriverId()+ "", "订单推送","有乘客需要乘车","");
                    MessagePushUtil.sendPushTryCatch(pushPayload);
                    while (!DriverPool.sendMessageByNickName(orderBean.getDriverNickName(), "sendMessage2driver:" + JsonUtil.json2str(orderBean))) {
                        try {
                            Thread.sleep(10000);
                            count++;
                            if (count >= 12) {
                                break;
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            break;
                        }
                    }
                });
            }

            map.put(Constants.MAP_KEY_RESULT, true);
            map.put(Constants.MAP_KEY_MESSAGE, JsonUtil.json2str(orderBean));
            return map;
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            return map;
        }

    }

    /**
     * 取消订单
     *
     * @param orderInfo {"orderId":4, "customerPhone":12345678910}
     * @return {"result": true}
     */
    @RequestMapping(value = "/cancelOrder", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Object cancelOrder(@RequestBody OrderInfo orderInfo) {
        Map<String, Boolean> map = new HashMap<>();

        int orderId = orderInfo.getOrderId();
        String customerPhone = orderInfo.getCustomerPhone();
        boolean result = false;
        if (orderId != 0 && customerPhone != null && !"".equals(customerPhone)) {

            int driverId = customerService.getDriverIdByOrderId(orderId);
            if (driverId != 0) {
                //先通过内存池中获取session，然后获取driver的Phone
                DriverSession session = DriverPool.getSessionById(driverId);
                session.setWork(false);
            }
            result = customerService.cancelOrder(orderInfo);
        }
        map.put(Constants.MAP_KEY_RESULT, result);
        return map;
    }

    /**
     * 查询当前订单
     *
     * @param hashMap {"customerPhone": "+8612345678910"}
     * @return {}
     */
    @RequestMapping(value = "/currentOrder", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map currentOrder(@RequestBody HashMap<String, String> hashMap) {
        logger.info("乘客查询当前订单：" + hashMap);
        Map map = new HashMap(2);

        String phone = "customerPhone";
        if (hashMap.get(phone) != null && hashMap.get(phone).contains("+")) {

            OrderBean orderBean = customerService.selectCurrentOrderByPhone(hashMap);
            if (orderBean == null) {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "没有当前订单！");
            } else {
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, orderBean);
            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "非法请求值！");
        }
        return map;
    }

    /**
     * 查询历史订单
     *
     * @param map {"customerPhone":"12345678910","totalCount":-1, "startCount": 2, "limitCounts": 3}
     * @return {"result": true,"message": [{"orderFinishTime": 1523350958000,"orderTravelOnPlace": "aaa","orderTravelEndPlace": "南京工业","totalCount": 0}],"totalCount": 8}
     */
    @RequestMapping(value = "/getHistoryOrders", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Object historyOrders(@RequestBody Map<String, Object> map) {
        Map<String, Object> result = new HashMap<>();
        List<Map> list;
        int counts = Integer.parseInt(map.get("totalCount").toString());
        int resultCount;
        //若传入的总数值不为-1则直接返回传入的值
        if (counts == -1) {
            resultCount = customerService.selectHistoryOrderCount(map);
        } else {
            resultCount = counts;
        }

        String customerPhone = (String) map.get("customerPhone");
        if (!"".equals(customerPhone)) {
            boolean isLogin = CustomerPool.isContain(customerPhone);
            if (isLogin) {
                list = customerService.selectHistoryOrder(map);
                if (list.size() == 0) {
                    result.put(Constants.MAP_KEY_RESULT, false);
                    result.put(Constants.MAP_KEY_MESSAGE, "您当前还没有订单信息！");
                } else {
                    result.put(Constants.MAP_KEY_RESULT, true);
                    result.put(Constants.MAP_KEY_MESSAGE, list);
                    result.put(Constants.MAP_KEY_TOTAL_COUNT, resultCount);
                }
            } else {
                result.put(Constants.MAP_KEY_RESULT, false);
                result.put(Constants.MAP_KEY_MESSAGE, Constants.MAP_VALUE_ILLEGAL_REQUEST);
            }
        } else {
            result.put(Constants.MAP_KEY_RESULT, false);
            result.put(Constants.MAP_KEY_MESSAGE, Constants.MAP_VALUE_ILLEGAL_REQUEST);
        }
        return result;
    }

    /**
     * 评价
     *
     * @param appraiseBean {"driverId":31,"orderId":1, "appraiseStars":5,"appraiseContent":"非常好"}
     * @return {"result": true}
     */
    @RequestMapping(value = "/appraiseOrder", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Object appraise(@RequestBody AppraiseBean appraiseBean) {
        Map<String, Object> map = new HashMap<>();
        int star = appraiseBean.getAppraiseStars();
        int driverId = appraiseBean.getDriverId();
        double creditAction = 0;
        switch (star) {
            case 5:
                creditAction = 1;
                if (TimeUtils.isInDate(new Date(), Constants.BEGIN_DATE, Constants.END_DATE)) {
                    creditAction *= creditAction;
                }
                driverService.insertDriverCredit(new CreditBean(driverId, creditAction, Constants.STAR_5));
                break;
            case 4:
                creditAction = 0.5;
                driverService.insertDriverCredit(new CreditBean(driverId, creditAction, Constants.STAR_4));
                break;
            case 3:
                creditAction = 0;
                driverService.insertDriverCredit(new CreditBean(driverId, creditAction, Constants.STAR_3));
                break;
            case 2:
                creditAction = -1;
                driverService.insertDriverCredit(new CreditBean(driverId, creditAction, Constants.STAR_2));
                break;
            case 1:
                creditAction = -2;
                driverService.insertDriverCredit(new CreditBean(driverId, creditAction, Constants.STAR_1));
                break;
            case 0:
                creditAction = -0.5;
                driverService.insertDriverCredit(new CreditBean(driverId, creditAction, Constants.STAR_0));
                break;
            default:
                break;
        }
        boolean b = customerService.insertAppraiseOrder(appraiseBean);
        if (b) {
            map.put(Constants.MAP_KEY_RESULT, true);
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "订单已评价");
        }
        return map;
    }

    /**
     * 获取常用地址
     *
     * @return {"result": true}
     */
    @RequestMapping(value = "/getUsualAddr", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Object usualAddr() {
        Map<String, Object> map = new HashMap<>();
        map.put(Constants.MAP_KEY_RESULT, true);
        map.put(Constants.MAP_KEY_MESSAGE, customerService.selectUsualAddr());
        return map;
    }

    /**
     * 根据地址名称获取地址详细信息、经纬度 {"addressName":"UBC"}
     *
     * @param addr addrName
     * @return {"result": true}
     */
    @RequestMapping(value = "/getUsualAddrByName", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Object getUsualAddrByName(@RequestBody UsualAddr addr) {
        Map<String, Object> map = new HashMap<>();
        UsualAddr usualAddr = customerService.selectUsualAddrByName(addr.getAddrName());
        if ("".equals(addr.getAddrName())) {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "未知错误");
        } else if (usualAddr == null) {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "没有这样的地方！");
        } else {
            map.put(Constants.MAP_KEY_RESULT, true);
            map.put(Constants.MAP_KEY_MESSAGE, usualAddr);
        }
        return map;
    }

    /**
     * 乘客发送经纬度和车型获取推荐司机
     *
     * @param requestMap {"startAddress":{"lat":11.1111111111,"lng":111.111111111},"carType":"SUV四座","userPhone":"+8612345678910"}
     * @return {"result":true,"message":[]}
     */
    @RequestMapping(value = "/getRecommends", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Object getRecommends(@RequestBody Map requestMap) {
        Map map = new HashMap();
        if (requestMap.get("userPhone") == null || requestMap.get("startAddress") == null || requestMap.get("carType") == null) {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, Constants.MAP_VALUE_ILLEGAL_REQUEST);
        } else {
            Map paramMap = (Map) requestMap.get("startAddress");
            if ("".equals(requestMap.get("carType").toString())) {
                paramMap.put("carType", "%");
            } else {
                paramMap.put("carType", requestMap.get("carType"));
            }

            List<DriverSession> list = DriverPool.getTop10(Double.parseDouble(paramMap.get("lat").toString()), Double.parseDouble(paramMap.get("lng").toString()), paramMap.get("carType").toString(), Integer.parseInt(requestMap.get("userNum").toString()));

            String param = "";
            JsonObject obj = null;
            JsonObject object = null;

            for (DriverSession driverSession : list) {
                param = Constants.ROAD_REQUEST_PARAM + "&origin=" + paramMap.get("lat") + "," + paramMap.get("lng") + "&destination=" + driverSession.getLat() + "," + driverSession.getLng();
                String sendGet = HttpRequestUtil.sendGet(Constants.ROAD_REQUEST, param);
                logger.info("customer_getRecommends_sendGet:" + sendGet);
                try {
                    obj = JsonUtil.str2obj(sendGet, JsonObject.class);
                    object = obj.getAsJsonArray("routes").get(0).getAsJsonObject().getAsJsonArray("legs").get(0).getAsJsonObject().get("distance").getAsJsonObject();
                    driverSession.setDistance(object.get("value").getAsInt());
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.warn("获取推荐司机时候出现解析异常：" + e + "\n" + e.getMessage());
                    driverSession.setDistance(100000000.000);
                }
            }

            Collections.sort(list, new Comparator<DriverSession>() {
                @Override
                public int compare(DriverSession o1, DriverSession o2) {
                    return (int) Math.round(o1.getDistance() - o2.getDistance());
                }
            });

            if (list.size() >= Constants.RECOMMEND_NUM) {
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, list.subList(0, 5));
            } else {
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, list);
            }
        }

        return map;
    }

    /**
     * 乘客端需要获取九张图片列表
     *
     * @param hashMap {"AWCCIS_CODE":"1a5da935ac641f2c46d5096f08d0c40b15234072"}
     * @return {}
     */
    @RequestMapping(value = "/showAdverImg", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map showAdverImg(@RequestBody HashMap<String, String> hashMap) {
        logger.info("customer获取九张图片列表信息" + hashMap);
        Map<String, Object> map = new HashMap<>(2);

        String code = "AWCCIS_CODE";
        List<AdverImgLocationBean> list;
        if (hashMap.get(code) != null && Constants.AWCCIS_CODE.equals(hashMap.get(code))) {
            list = customerService.getAdverImgPath();
            if (list.size() > 0) {
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, list);
            } else {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "出错啦！");
            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "请求值非法！");
        }
        return map;
    }

    /**
     * 新增广告接口showAdverImg1,从数据库中t_current_logo表获取的9张图片中随机选一张返回给前端
     *
     * @param hashMap {"AWCCIS_CODE":"1a5da935ac641f2c46d5096f08d0c40b15234072"}
     * @return {"result":true,"message":[{"currentId":7,"currentLogoPath":"upload/adverimg/12313123213.jpg"}]}
     */
    @RequestMapping(value = "/showAdverImg1")
    @ResponseBody
    public Object showAdverImg1(@RequestBody HashMap<String, String> hashMap) {
        logger.info("customer获取九张图片列表信息" + hashMap);
        Map<String, Object> map = new HashMap<>(2);

        String code = "AWCCIS_CODE";
        List<AdverImgLocationBean> list;
        if (hashMap.get(code) != null && Constants.AWCCIS_CODE.equals(hashMap.get(code))) {
            list = customerService.getAdverImgPath();
            List<AdverImgLocationBean> list1 = new ArrayList<>();
            list1.add(list.get((int) (Math.random() * list.size())));
            if (list1.size() > 0) {
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, list1);
            } else {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "出错啦！");
            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "请求值非法！");
        }
        return map;
    }

    /**
     * 新增广告接口showAdverImg2,从数据库中t_logo表随机获取一个广告图片返回给前端
     *
     * @param hashMap {"AWCCIS_CODE":"1a5da935ac641f2c46d5096f08d0c40b15234072"}
     * @return {"result":true,"message":[{"currentId":7,"currentLogoPath":"upload/adverimg/12313123213.jpg"}]}
     */
    @RequestMapping(value = "/showAdverImg2")
    @ResponseBody
    public Object showAdverImg2(@RequestBody HashMap<String, String> hashMap) {
        Map<String, Object> map = new HashMap<>(2);

        String code = "AWCCIS_CODE";
        List<AdverImgLocationBean> list;
        if (hashMap.get(code) != null && Constants.AWCCIS_CODE.equals(hashMap.get(code))) {
            list = customerService.getOneRandomLogoPathByCode();
            logger.info("customerService.getOneRandomLogoPath();" + list);
            if (list.size() > 0) {
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, list);
            } else {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "出错啦！");
            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "请求值非法！");
        }
        return map;
    }

    /**
     * 根据ID查询乘客的预约订单
     *
     * @param hashMap {"customerId": 100642}
     * @return {}
     */
    @RequestMapping(value = "/selectServiceOrders", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Map<String, Object> selectServiceOrders(@RequestBody HashMap<String, Integer> hashMap) {
        logger.info("用户请求查看预约订单：" + hashMap);
        Map<String, Object> map = new HashMap<>();

        String id = "customerId";
        if (hashMap.get(id) != null && hashMap.get(id) != 0) {
            List<ServiceOrderSimpleBean> list = customerService.getCusotmerServiceOrderById(hashMap.get(id));
            if (list.size() > 0) {
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, list);
            } else {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "当前没有预约订单");
            }
        }
        return map;
    }

    /**
     * 记录访问量
     *
     * @param requestMap 请求参数
     * @param request    request
     * @return 访问信息
     */
    @RequestMapping(value = "/visitInfo", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Object visitInfo(@RequestBody Map requestMap, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("date", System.currentTimeMillis());
        map.put("os", requestMap.get("os"));
        map.put("model", requestMap.get("model"));
        map.put("ip", request.getRemoteAddr());
        customerService.recordVisitInfo(map);
        return map;
    }
}